package xyz.zchao.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.Category;
import xyz.zchao.blog.service.CategoryService;
import xyz.zchao.blog.util.PageResultVO;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import javax.validation.Valid;
import java.util.List;

/**
 * @Description:
 * @Author: guozongchao
 * @Date: 2020/5/16 17:15
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @IgnoreToken
    @GetMapping("/list")
    public PageResultVO getCategories(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit) {
        List<Category> categories = categoryService.retrieveAllByPaging(page, limit);
        long count = categoryService.getCount();
        return new PageResultVO(ResultCode.SUCCESS, categories, count);
    }

    @IgnoreToken
    @GetMapping("/list/{cid}")
    public ResultVO getCategory(@PathVariable("cid") Integer cid) {
        Category category = categoryService.retrieveById(cid);
        return new ResultVO(ResultCode.SUCCESS, category);
    }

    @PutMapping("/list/{cid}")
    public ResultVO updateCategory(@PathVariable("cid") Integer cid, @RequestBody @Valid Category record) {
        record.setCategoryId(cid);
        categoryService.update(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @DeleteMapping("/list/{cid}")
    public ResultVO deleteCategory(@PathVariable("cid") Integer cid) {
        categoryService.deleteById(cid);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @PostMapping("/add")
    public ResultVO addCategory(@RequestBody @Valid Category record) {
        categoryService.create(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @IgnoreToken
    @GetMapping("/search")
    public ResultVO searchCategories(@RequestParam String keyword) {
        List<Category> categories = categoryService.findCategorysByName(keyword);
        return new ResultVO(ResultCode.SUCCESS, categories);
    }


}
